import Vue from 'vue'
import cookie from 'vue-cookie'
import router from '@/router'
import dateFormat from 'dateformat'
import {getUrl} from '@/utils/request'

export function btnBlur(evt) {
  if (window.R.isNil(evt)) {
    return
  }
  let target = evt.target

  if (target.nodeName.toUpperCase() === 'SPAN' || target.nodeName === 'I') {
    target = evt.target.parentNode
  }
  target.blur()
}

/**
 * 获取uuid
 */
export function getUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? Math.random() * 16 | 0 : 'r&0x3' | '0x8').toString(16)
  })
}

/**
 * 是否有权限
 * @param {*} key
 */
export function isAuth(key) {
  if (key === 'all') {
    return true
  }
  return JSON.parse(sessionStorage.getItem('permissions') || '[]').indexOf(key) !== -1 || false
}

export function isAuthForColumn(key) {
  if (window.R.isNil(key)) {
    return true
  }
  return isAuth(key)
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate(data, id = 'id', pid = 'parentId') {
  const res = []
  const temp = {}

  for (let i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (let k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = []
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]['_level'] + 1
      temp[data[k][pid]]['children'].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  return res
}

/**
 * 清除登录信息
 */
export function clearLoginInfo() {
  Vue.cookie.delete('token')
  // store.commit('resetStore')
  router.options.isAddDynamicMenuRoutes = false
}

/**
 * Check if an element has a class
 * @param {HTMLElement} ele
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return Boolean(ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)')))
}

/**
 * Add class to element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) {
    ele.className += ' ' + cls
  }
}

/**
 * Remove class from element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

/**
 * 获取格式化后的时间
 * @param date 时间对象
 * @param format 格式化字符串
 * @returns {string}
 */
export function getFormatDateTime(date = new Date(), format = 'yyyy-mm-dd HH:MM:ss') {
  if (date instanceof Date && !isNaN(date)) {
    return dateFormat(date, format)
  }
  return date
}

/**
 * 替换表单对象中的特殊值
 * @param data 需要煎炒的表单对象
 * @returns {*}
 */
export function specialTypeCheck(data) {
  // eslint-disable-next-line no-underscore-dangle
  const _data = window.R.clone(data)

  Object.keys(data).forEach((attr) => {
    if (/^autocompleteLabel-.+$/.test(attr)) {
      // eslint-disable-next-line no-undefined
      _data[attr] = undefined
    }
    if (window.R.equals('dateTimeRange', attr)) {
      const dateRange = data[attr]

      if (dateRange instanceof Array) {
        _data['startDateTime'] = getFormatDateTime(new Date(dateRange[0]))
        _data['endDateTime'] = getFormatDateTime(new Date(dateRange[1]))
      }
      // eslint-disable-next-line no-undefined
      _data[attr] = undefined
    }
  })
  return _data
}

export function downloadHandle(content, fileName) {
  const eleLink = document.createElement('a')

  eleLink.download = fileName
  eleLink.style.display = 'none'
  const blob = new Blob([content])

  eleLink.href = URL.createObjectURL(blob)
  document.body.appendChild(eleLink)
  eleLink.click()
  document.body.removeChild(eleLink)
}

export function exportHandle(exportApiName, option = {}) {
  window.location.href = getUrl(exportApiName, Object.assign(option, {token: cookie.get('token')}))

  // mRequest(exportApiName, option, (res) => {
  //   let fileName = '未命名'
  //   const disposition = window.R.path(['headers', 'content-disposition'], res)
  //
  //   if (!window.R.isNil(disposition)) {
  //     fileName = decodeURIComponent(disposition.match(/;filename=(.+)/)[1])
  //   }
  //   downloadHandle(window.R.propOr('数据为空', 'data', res), fileName)
  // }, {responseType: 'blob'})
}


/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

// 金额数字转大写
export function   digitUppercase(price) {
  const fraction = ['角', '分']
  const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  const unit = [
    ['元', '万', '亿'],
    ['', '拾', '佰', '仟']
  ]
  let num = Math.abs(price)
  let s = ''
  fraction.forEach((item, index) => {
    s += (digit[Math.floor(num * 10 * (10 ** index)) % 10] + item).replace(/零./, '')
  })
  s = s || '整'
  num = Math.floor(num)
  for (let i = 0; i < unit[0].length && num > 0; i += 1) {
    let p = ''
    for (let j = 0; j < unit[1].length && num > 0; j += 1) {
      p = digit[num % 10] + unit[1][j] + p
      num = Math.floor(num / 10)
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
  }

  return s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整')

}

// 时间快捷选项
export function timeShortcutOption1(){
  const pickerOptions = {
    shortcuts: [
      {
        text: '今天',
        onClick(picker) {
          let start = new Date();
          let end = new Date();
          if (picker) picker.$emit('pick', [start, end]);
          else return { start, end };
        }
      },
      {
        text: '昨天',
        onClick(picker) {
          let start = new Date();
          let end = new Date();
          start.setDate(start.getDate() - 1);
          end.setDate(end.getDate() - 1);
          if (picker) picker.$emit('pick', [start, end]);
          else return { start, end };
        }
      }, {
        text: '一周前',
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
          picker.$emit('pick', [start, end]);
        }
      }, {
        text: '一月后',
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
          picker.$emit('pick', [start, end]);
        }
      }
    ]
  }
  return pickerOptions
}

// 时间范围快捷选项
export function timeShortcutOption(){
  const pickerOptions = {
    shortcuts: [
      {
        text: '今天',
        onClick(picker) {
          let start = new Date();
          let end = new Date();
          if (picker) picker.$emit('pick', [start, end]);
          else return { start, end };
        }
      },
      {
        text: '昨天',
        onClick(picker) {
          let start = new Date();
          let end = new Date();
          start.setDate(start.getDate() - 1);
          end.setDate(end.getDate() - 1);
          if (picker) picker.$emit('pick', [start, end]);
          else return { start, end };
        }
      }, {
        text: '最近一周',
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
          picker.$emit('pick', [start, end]);
        }
      }, {
        text: '最近一个月',
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
          picker.$emit('pick', [start, end]);
        }
      }, {
        text: '最近三个月',
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
          picker.$emit('pick', [start, end]);
        }
      }
    ]
  }
  return pickerOptions
}